package com.example.socket.util;


import com.example.socket.ServletConstant;

import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname ServletQueryParamUtils
 * @Description TODO
 * @Date 2023/4/28 9:51
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class ServletQueryParamUtils {

    public static Pattern pattern_wwww_form = Pattern.compile("([^&=]+)=([^&=]+)");

    public static Map<String,List<String>> getQueryParamMap(String queryParam){
        Map<String, List<String>> params = new LinkedHashMap<>();
        String query = queryParam;
        if(query==null){
            return params;
        }
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            String key = idx > 0 ? pair.substring(0, idx) : pair;
            String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : null;
            if(!params.containsKey(key)){
                params.put(key,new ArrayList<>());
            }
            params.get(key).add(value);
        }
        return params;
    }

    public static Map<String, List<String>> getQueryFormParams(String queryStr){
        // 循环遍历匹配结果，并将参数名称和值存储到Map中
        Map<String, List<String>> params = new HashMap<>();
        try {
            Matcher matcher = pattern_wwww_form.matcher(queryStr);
            while (matcher.find()) {
                String paramName = matcher.group(1);
                String paramValue = matcher.group(2);
                // 对参数值进行URL解码
                paramValue = URLDecoder.decode(paramValue, ServletConstant.STRING_CODE);
                if(!params.containsKey(paramName)){
                    params.put(paramName,new ArrayList<>());
                }
                params.get(paramName).add(paramValue);
            }
            return params;
        }catch (Exception e){
            e.printStackTrace();
        }
        return params;
    }
}
